<?php

namespace StudyBuddy\Controllers;

use \StudyBuddy\WebPage;
use \StudyBuddy\Question;
use \StudyBuddy\Request;
use \StudyBuddy\Responder;

/**
 *
 * This contoller received the
 * "Close" form from the question
 * View and then depending on permission
 * of Viewer will either mark question
 * as closed or send request to close question
 * to Moderators
 *
 */
class Close extends WebPage
{
	protected $membersOnly = true;

	protected $requireToken = true;

	protected $bRequirePost = true;

	protected $aRequired = array('qid', 'reason');

	protected $oQuestion;

	protected $requested = false;

	/**
	 *
	 * Subject of email sent
	 * to moderators
	 *  @todo translate string
	 */
	const SUBJECT = 'Request to close question';

	/**
	 *
	 * Body of email sent to moderators
	 * when request to delete is made

	 * @todo stranslate string
	 */
	const EMAIL_BODY = '
	User: %1$s
	Profile: %2$s
	
	Requesting to close question: %3$s
	
	Title: %4$s
	
	Intro: %5$s
	
	Reason: %6$s
	
	Note: %7$s
	
	';


	protected function main(){

		$this->getQuestion()
		->setClosed()
		->returnResult();
	}


	protected function getQuestion(){
		$a = $this->oRegistry->Mongo->QUESTIONS->findOne(
		array(
		'_id' => $this->oRequest['qid'])
		);

		if(empty($a)){
			throw new \StudyBuddy\Exception('Question not found');
		}

		$this->oQuestion = new Question($this->oRegistry, $a);

		return $this;
	}


	/**
	 *
	 * If moderator then close it,
	 * if Not moderator then if owner - request closing
	 * of question
	 *
	 * @return object $this
	 */
	protected function setClosed(){
		try{
			$this->checkAccessPermission('close_question');
		} catch (\StudyBuddy\AccessException $e){
			if(!\StudyBuddy\isOwner($this->oRegistry->Viewer, $this->oQuestion)){
				throw $e;
			}

			return $this->requestClose();
		}

		$reason = $this->oRequest['reason'].'. '.$this->oRequest['note'];
		d('reason: '.$reason);

		$this->oQuestion->setClosed($this->oRegistry->Viewer, $reason);
		$this->oRegistry->Dispatcher->post($this->oQuestion, 'onQuestionClosed');

		return $this;
	}


	/**
	 * Send our emails to moderators requesting
	 * to close this question
	 *
	 * @return object $this
	 */
	protected function requestClose(){
		$cur = $this->oRegistry->Mongo->USERS->find(array(
  			'role' => array('$in' => array('moderator', 'administrator'))
		), array('email'));

		d('found '.$cur->count().' moderators');

		if($cur && $cur->count() > 0){
			$aModerators = iterator_to_array($cur, false);
			d('$aModerators '.print_r($aModerators, 1));
			$Mailer = \StudyBuddy\Mailer::factory($this->oRegistry);
			$body = $this->makeBody();
			$Mailer->mail($aModerators, self::SUBJECT, $body);
		}

		$this->requested = true;

		return $this;
	}


	/**
	 * Make body of the email
	 * which will be sent to moderators
	 *
	 * @return string body of email
	 */
	protected function makeBody(){
		$vars = array(
		$this->oRegistry->Viewer->getDisplayName(),
		$this->oRegistry->Ini->SITE_URL.$this->oRegistry->Viewer->getProfileUrl(),
		$this->oQuestion->getUrl(),
		$this->oQuestion['title'],
		$this->oQuestion['intro'],
		$this->oRequest['reason'],
		$this->oRequest['note']
		);

		d('vars: '.print_r($vars, 1));

		$body = vsprintf(self::EMAIL_BODY, $vars);

		d('body '.$body);

		return $body;
	}


	protected function returnResult(){
		/**
		 * @todo translate string
		 */
		$message = 'Question closed';
		$requested = 'A request to close
		this question has been sent to moderators<br>
		The final decision about closing the question or leaving it open will be up to moderators';


		if(Request::isAjax()){
			$res = (!$this->requested) ? $message : $requested;
			$ret = array('alert' => $res);
			/**
			 * If item was actually deleted then
			 * add 'reload' => 2 to return
			 * which will cause page reload
			 * in 1.5 seconds.
			 */
			if(!$this->requested){
				$ret['reload'] = 1500;
			}


			Responder::sendJSON($ret);
		}

		Responder::redirectToPage($this->oResource->getUrl());
	}

}
